﻿using System;
using System.Configuration;
using System.Web.Mvc;
using log4net;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;

namespace Matrix.MaKaYunShang.WeChat.Controllers
{
    /// <summary>
    /// 蓝马管家接口CONTROLLER
    /// </summary>
    public class MkysMcMagController : BaseInterfaceController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(MkysMcMagController));

        #region Actions
        /// <summary>
        /// 公众号微信接口入口
        /// </summary>
        /// <returns></returns>
        public ActionResult WxInterface()
        {
            if (Request.Url == null)
            {
                return View();
            }

            var nWxInterfaceUrlIndex = Request.RawUrl.IndexOf("/WxInterface", StringComparison.Ordinal);
            var strPjCode = Request.RawUrl.Substring(1, nWxInterfaceUrlIndex - 1);

#if DEBUG
            _fileLog.Info("MkysMcMagController | WxInterface Request " + Request.Url.AbsoluteUri);
#endif

            #region 验证签名分支
            var wxSignatureToken = ConfigurationManager.AppSettings["MkysMcSignatureToken"];
            var result = CheckSingatureProcess(strPjCode, wxSignatureToken);
            if (result != null)
            {
                return result;
            }
            #endregion

            try
            {
                //获取当前云迈云中心项目资料
                var pjResult = GetCurrentMatrixCloudProjectInfo(strPjCode);
                if (!pjResult.Status)
                {
                    return View();
                }

#if DEBUG
                _fileLog.Info("MkysMcMagController | WxInterface Event Request" + System.Web.HttpContext.Current.Request.InputStream);
#endif

                string strMsgType;
                string strJsonContent;

                //分析微信服务端POST到接口的数据，并获取公众号信息
                var wechatInfo = AnalysisWxPostData(out strMsgType, out strJsonContent);
                if (wechatInfo == null || wechatInfo.Id == 0)
                {
                    return View();
                }
                //根据MsgType调用分支处理流程
                //根据微信开发WIKI，保证在五秒内处理并回复，采用直接SUCCESS
                var strReplayXmlContent = "success";
                switch (strMsgType.ToLower())
                {
                    case "event":
                        strReplayXmlContent = WxEventProcess(strJsonContent, wechatInfo);
                        break;
                    case "text":
                    case "image":
                    case "voice":
                    case "video":
                    case "shortvideo":
                    case "link":
                    case "location":
                        strReplayXmlContent = WxMsgProcess(strJsonContent, wechatInfo);
                        break;
                }
#if DEBUG
                _fileLog.Info("MkysMcMagController | WxInterface : Return message content - " + strReplayXmlContent);
#endif

                if (!string.IsNullOrWhiteSpace(strReplayXmlContent))
                {
                    Response.ContentType = "text/xml";
                    Response.Write(strReplayXmlContent);
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysMcMagController | WxInterface : Exception - " + ex.Message + ex.StackTrace);
            }

            return View();
        }

        /// <summary>
        /// 公众号签名验证
        /// </summary>
        /// <param name="signatureToken"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        public ActionResult CheckSignature(string signatureToken, string signature, string timestamp, string nonce,
            string echostr)
        {
            var strResult = CheckSignatureFunc(signatureToken, signature, timestamp, nonce, echostr);

            ViewBag.PostValue = strResult;

            return View();
        }

        /// <summary>
        /// 微信登录验证回调接口，处理完毕并跳回验证前提供的回调地址
        /// </summary>
        /// <returns></returns>
        public ActionResult WxAuthUserToken()
        {
            string strRedirectUrl;

            var nWxInterfaceUrlIndex = Request.RawUrl.IndexOf("/WxAuthUserToken", StringComparison.Ordinal);
            var strPjCode = Request.RawUrl.Substring(1, nWxInterfaceUrlIndex - 1);
            //获取当前云迈云中心项目资料
            var pjResult = GetCurrentMatrixCloudProjectInfo(strPjCode);
            if (!pjResult.Status)
            {
                return View();

            }

            WxAuthUserTokenFunc(out strRedirectUrl);

            if (!string.IsNullOrWhiteSpace(strRedirectUrl))
            {
                Response.Redirect(strRedirectUrl);
            }
            return View();
        }

        /// <summary>
        /// 第三方登录验证接口
        /// </summary>
        /// <param name="callBackUrlEncode"></param>
        /// <returns></returns>
        public ActionResult WxOAutherize(string callBackUrlEncode)
        {
            var nWxInterfaceUrlIndex = Request.RawUrl.IndexOf("/WxOAutherize", StringComparison.Ordinal);
            var strPjCode = Request.RawUrl.Substring(1, nWxInterfaceUrlIndex - 1);
            //获取当前云迈云中心项目资料
            var pjResult = GetCurrentMatrixCloudProjectInfo(strPjCode);
            if (!pjResult.Status)
            {
                return View();
            }

            var strAuthUrl = WxOAutherizeFunc(callBackUrlEncode);
            if (!string.IsNullOrWhiteSpace(strAuthUrl))
            {
                Response.Redirect(strAuthUrl);
            }
            return View();
        }
        #endregion

        #region Private Methods


        /// <summary>
        /// 处理微信上行的消息逻辑
        /// </summary>
        /// <param name="weChatMsgRev"></param>
        /// <param name="wechatInfo"></param>
        /// <returns></returns>
        public override string DealMsg(MxApiWeChatMsgRev weChatMsgRev, MxApiWechatInfo wechatInfo)
        {
            //根据微信开发WIKI，保证在五秒内处理并回复，采用直接SUCCESS
            const string strDefaultMsg = "success";
            if (wechatInfo == null || string.IsNullOrWhiteSpace(wechatInfo.AppId) ||
                string.IsNullOrWhiteSpace(wechatInfo.Secret))
            {
                _fileLog.Error("MkysMcMagController | DealMsg | None WechatMp Info - ");
                return strDefaultMsg;
            }

            if (weChatMsgRev == null)
            {
                _fileLog.Error("MkysMcMagController | DealMsg | Received message is empty");
                return strDefaultMsg;
            }

#if DEBUG
            _fileLog.Info("MkysMcMagController | DealMsg : received message content - " + weChatMsgRev.MsgId);
#endif

            try
            {
                var resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 1,
                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                if (!resultReply.Status)
                {
                    resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 0,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (!resultReply.Status)
                    {
                        return string.Empty;
                    }
                }
                return resultReply.Data;
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysMcMagController | DealMsg : Exception - " + ex.Message + ex.StackTrace);
            }
            return string.Empty;
        }

        /// <summary>
        /// 处理微信上行的事件逻辑
        /// </summary>
        /// <param name="wechatEventHistory"></param>
        /// <param name="wechatInfo"></param>
        /// <returns></returns>
        public override string DealEvent(MxApiWechatEventHistory wechatEventHistory, MxApiWechatInfo wechatInfo)
        {
#if DEBUG
            _fileLog.Info("MkysMcMagController | DealEvent Begin - " + wechatEventHistory.Event);
#endif

            var strRetContent = string.Empty;

            switch (wechatEventHistory.Event.ToLower())
            {
                case "subscribe": //关注
                    strRetContent = SubscribeUser(wechatEventHistory, wechatInfo, 0);
                    break;
                case "unsubscribe": //取消订阅
                    UnsubscribeUser(wechatEventHistory, wechatInfo);
                    break;
                case "scan": //用户已关注时的事件推送
                    if (!string.IsNullOrWhiteSpace(wechatEventHistory.EventKey) &&
                        !string.IsNullOrWhiteSpace(wechatEventHistory.Ticket))
                    {
                        strRetContent = SubscribeUser(wechatEventHistory, wechatInfo, 1);
                    }
                    break;
                
                case "location": //上报地理位置事件
                    AddNewLoctationInfo(wechatEventHistory, wechatInfo);
                    strRetContent = string.Empty;
                    break;
                case "click": //自定义菜单事件
                case "view": //点击菜单跳转链接时的事件推送
                case "card_pass_check"://卡券通过审核
                case "card_not_pass_check"://卡券未通过审核
                case "user_get_card"://用户领取卡券
                case "user_del_card"://用户删除卡券
                case "user_consume_card"://核销事件
                case "User_pay_from_pay_cell"://微信买单事件
                case "user_view_card": //进入会员卡事件推送
                case "user_enter_session_from_card"://用户从卡券进入公众号会话
                case "card_pay_order": //券点流水详情事件(朋友的券)
                    //var wechatCardEntries = new WechatCardEntries(wechatEventHistory, wechatInfo);
                    //wechatCardEntries.CardEventProccess();
                    //break;
                case "masssendjobfinish": //群发事件推送群发结果
                    strRetContent = string.Empty;
                    break;
                default:
                    var weChatMsgRev = new MxApiWeChatMsgRev
                    {
                        FromUserName = wechatEventHistory.FromUserName,
                        MsgType = "text"
                    };
                    var resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 0,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (resultReply.Status)
                    {
                        strRetContent = resultReply.Data;
                    }
                    else
                    {
                        strRetContent = string.Empty;
                    }
                    break;
            }

            return strRetContent;
        }

        /// <summary>
        /// 取消关注处理逻辑
        /// </summary>
        /// <param name="wechatEvent"></param>
        /// <param name="wechatInfo"></param>
        public override void UnsubscribeUser(MxApiWechatEventHistory wechatEvent, MxApiWechatInfo wechatInfo)
        {
            var userOpenId = wechatEvent.FromUserName;

            try
            {
                var wechatUserResult = MatrixCloudCenterInterFuncBllObj.GetWechatUserInfo(userOpenId,
                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                if (!wechatUserResult.Status || wechatUserResult.Data == null || wechatUserResult.Data.Id <= 0 ||
                    string.IsNullOrWhiteSpace(wechatUserResult.Data.OpenId))
                {
                    _fileLog.Error(
                        "MkysMcMagController | UnsubscribeUser : Cannot get wechat user info from Matrix-Cloud-Center - " +
                        wechatUserResult.Message);
                    return;
                }
                var wechatUser = wechatUserResult.Data;

                wechatUser.Subscribe = false;
                wechatUser.UnSubscribeTime = DateTime.Now;

                MatrixCloudCenterInterFuncBllObj.UpdateWechatInfoUserToMatrixCloud(wechatUser,
                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);

#if DEBUG
                _fileLog.Info("MkysMcMagController | UnsubscribeUser : Update user subscribe status to unsubscribe - " +
                              wechatEvent.FromUserName);
#endif
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysMcMagController | UnsubscribeUser : Exception - " + ex.Message + ex.StackTrace);
            }

        }

        /// <summary>
        /// 用户关注事件处理逻辑
        /// </summary>
        /// <param name="wechatEventHistory"></param>
        /// <param name="wechatInfo"></param>
        /// <param name="scanSource"></param>
        /// <returns></returns>
        private string SubscribeUser(MxApiWechatEventHistory wechatEventHistory, MxApiWechatInfo wechatInfo,
            int scanSource)
        {
#if DEBUG
            _fileLog.Info("MkysMcMagController | SubscribeUser | Begin - " + wechatEventHistory.Event);
#endif
            //构建用于处理下发用户消息的信息参数实体
            var weChatMsgRev = new MxApiWeChatMsgRev
            {
                WechatInfoId = wechatInfo.Id,
                FromUserName = wechatEventHistory.FromUserName,
                Content = scanSource == 0 ? "event_subscribe" : "event_scan",
                MsgType = scanSource == 0 ? "event_subscribe" : "event_scan"
            };

            try
            {
                var wechatUserResult =
                    MatrixCloudCenterInterFuncBllObj.SyncWechatUserFullInfoFromWechatToMatrixCloud(
                        wechatEventHistory.FromUserName, CurrentMatrixCloudProjectInfo.PjMcId,
                        CurrentMatrixCloudProjectInfo.PjSecret);
                if (!wechatUserResult.Status)
                {
                    _fileLog.Info(
                        "MkysMcMagController | SubscribeUser | SyncWechatUserFullInfoFromWechatToMatrixCloud error - " +
                        wechatUserResult.Message);
                    var resultAutoReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 0,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (resultAutoReply.Status && string.IsNullOrWhiteSpace(resultAutoReply.Data))
                    {
                        return resultAutoReply.Data;
                    }
                    return string.Empty;
                }

                if (wechatUserResult.StatusCode == 1)
                {
#if DEBUG
                    _fileLog.Info("MkysMcMagController | SubscribeUser | Add and sync user info to matrix cloud - ");
#endif
                    #region 扫描带参数的二维码关注  获取参数二维码绑定的商家后台用户ID
                    if (!string.IsNullOrWhiteSpace(wechatEventHistory.Ticket))
                    {
                        var weChatParamQrCodeResult =
                        MatrixCloudCenterInterFuncBllObj.GetParamQrCodeByWechatTiket(wechatEventHistory.Ticket,
                            CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                        if (weChatParamQrCodeResult.Status && weChatParamQrCodeResult.Data != null &&
                            weChatParamQrCodeResult.Data.Id > 0)
                        {
                            var mcAccountsBll = new McAccountsBLL();
                            var mcAccount = mcAccountsBll.GetModelByParamQrCodeId(weChatParamQrCodeResult.Data.Id, CurrentMatrixCloudProjectInfo);

                            if (mcAccount != null && mcAccount.Id > 0 && mcAccount.MxWechatInfoUserId == 0)
                            {
                                mcAccount.MxWechatInfoUserId = wechatUserResult.Data.WiuId;
                                mcAccountsBll.Update(mcAccount);
#if DEBUG
                                _fileLog.Info(
                                    "MkysMcMagController | SubscribeUser | Relate the McAccount to Wechat User Id - OpenId" +
                                    wechatUserResult.Data.OpenId + ", mcAccount id - " + mcAccount.Id);
#endif
                            } 
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysMcMagController | SubscribeUser : Exception - " + ex.Message + ex.StackTrace);
            }

            var resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 1,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
            if (resultReply.Status && string.IsNullOrWhiteSpace(resultReply.Data))
            {
                return resultReply.Data;
            }
            return string.Empty;
        }

        #endregion
    }
}
